from PyQt5.QtWidgets import (QWidget, QLabel, QVBoxLayout, QHBoxLayout,
                             QPushButton, QRadioButton, QButtonGroup, QFrame,
                             QScrollArea, QTextEdit, QSizePolicy)  # 添加 QSizePolicy
from PyQt5.QtCore import Qt
import sys
from io import StringIO
from Data.Chinese import model_number
from Data.Chinese import hardware
from Data.English import hardware_en


class OutputInterceptor(StringIO):
    def __init__(self, label):
        super().__init__()
        self.label = label
        self.original_stdout = sys.stdout

    def write(self, text):
        super().write(text)
        current_text = self.label.toPlainText()
        if current_text:
            # 添加新文本到现有内容后面
            self.label.append(text.rstrip())
            # 滚动到最新内容
            self.label.verticalScrollBar().setValue(
                self.label.verticalScrollBar().maximum()
            )
        else:
            self.label.setText(text.rstrip())
        # 刷新显示
        self.label.repaint()


class HardwareUI(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()
        # 连接语言切换信号
        self.window().lang_combo.currentTextChanged.connect(self.on_language_changed)
        # 根据当前语言设置默认选中项
        self.set_default_selection(self.window().lang_combo.currentText())

    def set_default_selection(self, language):
        # 根据语言设置默认选中项
        if language == "中文":
            self.revision_radio.setChecked(True)
        else:
            self.revision_radio.setChecked(True)  # 英文模式下也选中这个按钮，文本会在on_language_changed中更新

    def on_language_changed(self, language):
        # 获取修订记录版本按钮
        revision_button = [btn for btn in self.button_group.buttons()
                           if btn.text() in ["修订记录版本", "中文手册版本"]][0]
        # 根据语言设置更新按钮文本
        revision_button.setText("修订记录版本" if language == "中文" else "中文手册版本")
        # 设置默认选中项
        self.set_default_selection(language)

    def run_process(self):
        # 清空之前的信息
        self.info_label.clear()

        # 获取当前语言设置
        lang_combo = self.window().lang_combo
        is_chinese = lang_combo.currentText() == '中文'

        # 获取选中的按钮文本
        selected_button = self.button_group.checkedButton()
        version_type = selected_button.text()

        # 对英文模式下的"修订记录版本"进行特殊处理
        if not is_chinese and version_type == "修订记录版本":
            version_type = "中文手册版本"

        # 设置输出重定向
        output_interceptor = OutputInterceptor(self.info_label)
        sys.stdout = output_interceptor

        try:
            # 获取文件选择类型
            is_folder = self.folder_radio.isChecked()
            # file_type = "folder" if is_folder else "file"
            # 更新信息显示
            print(f"运行处理，版本类型：{version_type}，当前语言：{'中文' if is_chinese else '英文'}")
            if is_chinese:
                if version_type == "封面版本":
                    # print("封面版本")
                    hardware.hardware_manual(version_type, is_folder)
                    # model_number.rename_cover()
                elif version_type == "修订记录版本":
                    # print("修订记录版本")
                    hardware.hardware_manual(version_type, is_folder)
                    # model_number.rename_revision()
                else:  # 封面版本+1
                    hardware.hardware_manual(version_type, is_folder)
                    # print("封面版本+1")
                    # model_number.rename_cover_plus()
            else:
                if version_type == "封面版本":
                    # print("封面版本")
                    hardware_en.hardware_manual_en(version_type, is_folder)
                elif version_type == "中文手册版本":  # 修改这里的判断条件
                    # print("中文手册版本")
                    hardware_en.hardware_manual_en(version_type, is_folder)
                    # model_number_en.rename_revision()
                else:  # 封面版本+1
                    # print("封面版本+1")
                    hardware_en.hardware_manual_en(version_type, is_folder)
                    # model_number_en.rename_cover_plus()
        finally:
            # 恢复标准输出
            sys.stdout = output_interceptor.original_stdout

    def init_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(50, 30, 50, 30)  # 减小上下边距

        # 创建标题
        title = QLabel('硬件手册')
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet('font-size: 30px; color: #2c3e50; margin: 5px 0 15px 0;')

        # 第一组单选按钮（版本选择）
        version_container = QWidget()
        version_layout = QHBoxLayout(version_container)
        version_layout.setAlignment(Qt.AlignCenter)
        self.button_group = QButtonGroup()

        self.cover_radio = QRadioButton("封面版本")
        self.revision_radio = QRadioButton("修订记录版本")
        self.cover_plus_radio = QRadioButton("封面版本+1")

        # 第二组单选按钮（文件选择）
        file_container = QWidget()
        file_layout = QHBoxLayout(file_container)
        file_layout.setAlignment(Qt.AlignCenter)
        self.file_button_group = QButtonGroup()

        self.folder_radio = QRadioButton("选择文件夹")
        self.file_radio = QRadioButton("选择文件")
        self.folder_radio.setChecked(True)  # 默认选择文件夹

        # 设置单选按钮样式
        radio_style = """
            QRadioButton {
                font-size: 16px;
                color: #696969;
                padding: 3px;
                spacing: 8px;
                margin-top: 5px;
            }
            QRadioButton::indicator {
                width: 15px;
                height: 15px;
            }
        """

        # 设置按钮样式
        for radio in [self.cover_radio, self.revision_radio, self.cover_plus_radio,
                      self.folder_radio, self.file_radio]:
            radio.setStyleSheet(radio_style)

        # 添加按钮到按钮组
        self.button_group.addButton(self.cover_radio)
        self.button_group.addButton(self.revision_radio)
        self.button_group.addButton(self.cover_plus_radio)

        self.file_button_group.addButton(self.folder_radio)
        self.file_button_group.addButton(self.file_radio)

        # 添加按钮到布局
        version_layout.addWidget(self.cover_radio)
        version_layout.addSpacing(30)
        version_layout.addWidget(self.revision_radio)
        version_layout.addSpacing(30)
        version_layout.addWidget(self.cover_plus_radio)

        file_layout.addWidget(self.folder_radio)
        file_layout.addSpacing(30)
        file_layout.addWidget(self.file_radio)

        # 创建运行按钮
        run_button = QPushButton('运行')
        run_button.setFixedSize(200, 40)
        run_button.setStyleSheet("""
            QPushButton {
                background-color: #1E90FF;
                color: white;
                border: none;
                border-radius: 6px;
                font-size: 16px;
            }
            QPushButton:hover {
                background-color: #c0392b;
            }
            QPushButton:pressed {
                background-color: #a93226;
            }
        """)
        run_button.clicked.connect(self.run_process)

        # 创建分割线
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setStyleSheet("background-color: #A9A9A9;")
        line.setFixedHeight(2)

        # 创建信息显示区域
        self.info_label = QTextEdit()
        self.info_label.setReadOnly(True)
        self.info_label.setStyleSheet("""
            QTextEdit {
                color: #228B22;
                font-size: 14px;
                font-family: "Microsoft YaHei";
                margin-top: 10px;
                background-color: #F0FFF0;
                border: none;
                padding: 10px;
                line-height: 1.5;
            }
        """)
        self.info_label.document().setMaximumBlockCount(1000)  # 限制最大行数

        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidget(self.info_label)
        scroll_area.setWidgetResizable(True)
        scroll_area.setStyleSheet("""
            QScrollArea {
                border: none;
                background-color: #F0FFF0;
            }
            QScrollBar:vertical {
                width: 10px;
                background: #F0FFF0;
            }
            QScrollBar::handle:vertical {
                background: #A9A9A9;
                border-radius: 5px;
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                height: 0px;
            }
        """)
        scroll_area.setMinimumHeight(300)
        scroll_area.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        # 添加所有组件到主布局
        layout.addWidget(title)
        layout.addWidget(version_container)
        layout.addSpacing(5)
        layout.addWidget(file_container)
        layout.addSpacing(15)
        layout.addWidget(run_button, alignment=Qt.AlignCenter)
        layout.addSpacing(10)
        layout.addWidget(line)
        layout.addWidget(scroll_area, 1)
